package com.api.gbhg.liuwenbo.version2.api;

import com.alibaba.fastjson.JSON;
import com.api.formmode.page.util.Util;
import com.api.gbhg.liuwenbo.version2.dao.DataBaseUtil2;
import com.api.gbhg.liwenjun.VersionFlowUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 支出预算
 */
@Path("gb/ExpenditureBudgetApi")
public class ExpenditureBudgetApi {

    @POST
    @Path("/getDataList")
    @Produces(MediaType.APPLICATION_JSON)
    public String getDataList(Map<String,Object> param){
        Map<String,Object> msgMap = new HashMap<>();

        /**
         * kmkxj:1 (科目下级)
         * srlx:0
         * yslylx:"当年预算id:"9 , 11"
         * id+
         * dataid:"13,14"
         * dlhsdw
         * dfczbkxm
         * fzysrfl
         */
        //检查参数是否合法
        if (!param.containsKey("id") || !param.containsKey("kmjxj") || !param.containsKey("srlx") ||
                !param.containsKey("yslylx") || !param.containsKey("dataid") || !param.containsKey("dlhsdw")
                || !param.containsKey("dfczbkxm") || !param.containsKey("fzysrfl") || !param.containsKey("nf")
                || !param.containsKey("pageSize") || !param.containsKey("pageNum")){
            msgMap.put("code",204);
            msgMap.put("msg","非法参数！");
            msgMap.put("data","");
            return JSON.toJSONString(msgMap);
        }


        try {
            List<Map<String,Object>> data = getData(param);
            msgMap.put("code",200);
            msgMap.put("msg","success");
            msgMap.put("data",data);
            msgMap.put("dataTotal",getCountData(param));
        } catch (Exception e) {
            e.printStackTrace();
            msgMap.put("code",500);
            msgMap.put("msg","程序异常:"+e.toString());
            msgMap.put("data","");
            return JSON.toJSONString(msgMap);
        }
        return JSON.toJSONString(msgMap);
    }

    public String getCountData(Map<String,Object> param){
        RecordSet rs = new RecordSet();
        String dlhsdw = param.get("dlhsdw").toString();
        String nf = param.get("nf").toString();

        String condition1 = splicingConditions(param.get("kmjxj").toString(), param.get("id").toString(), param.get("dataid").toString(),
                param.get("srlx").toString(), param.get("yslylx").toString(),
                param.get("dfczbkxm").toString(), param.get("fzysrfl").toString());


        StringBuffer condition2 = new StringBuffer();
        if (!dlhsdw.isEmpty())
            condition2.append(" and dlhsdw="+dlhsdw+" ");

        if (!nf.isEmpty())
            condition2.append(" and ysnd="+nf+" ");

        String sql = "select count(id) cnt from uf_jingfei_version where lcjlsqjlid in( " +
                " select lcid from uf_jingfeilaiyuan where 1=1 "+condition1+" " +
                " and lcid in (select lcjlsqjlid from uf_jingfei_version where lcztz=3 "+condition2+") " +
                ") ";

        rs.executeQuery(sql);
        rs.next();

        return rs.getString("cnt");
    }

    public List<Map<String,Object>> getData(Map<String,Object> param){
        List<Map<String,Object>> dataList = new LinkedList<>();
        RecordSet rs = new RecordSet();
        RecordSet tempRs = new RecordSet();
        String dlhsdw = param.get("dlhsdw").toString();
        String nf = param.get("nf").toString();

//        String sql = "select dlhsdw,sbdw,xmmin,yszje from uf_jingfei_version where lcztz=3 ";

        String condition1 = splicingConditions(param.get("kmjxj").toString(), param.get("id").toString(), param.get("dataid").toString(),
                param.get("srlx").toString(), param.get("yslylx").toString(),
                param.get("dfczbkxm").toString(), param.get("fzysrfl").toString());


        StringBuffer condition2 = new StringBuffer();
        if (!dlhsdw.isEmpty())
            condition2.append(" and dlhsdw="+dlhsdw+" ");

        if (!nf.isEmpty())
            condition2.append(" and ysnd="+nf+" ");

        String sql = "select * from uf_jingfei_version where lcjlsqjlid in( " +
                " select lcid from uf_jingfeilaiyuan where 1=1 "+condition1+" " +
                " and lcid in (select lcjlsqjlid from uf_jingfei_version where lcztz=3 "+condition2+") " +
                ") ";

        String pageSize = param.get("pageSize").toString().isEmpty()?"10":param.get("pageSize").toString();

        Integer pageNum = (Integer.valueOf(param.get("pageNum").toString())-1)*Integer.valueOf(pageSize);
        if (!nf.isEmpty())
            sql += " order by requestid offset "+pageNum+" rows fetch next "+pageSize+" rows only ";

        rs.executeQuery(sql);
        while (rs.next()){
            Map<String,Object> dataMap = new HashMap<>();
            String dlhsdwName = Util.null2String(DataBaseUtil2.getSubcompanyNameById(rs.getString("dlhsdw")));
            String sbdwName = Util.null2String(DataBaseUtil2.getSubcompanyNameById(rs.getString("sbdw")));
            dataMap.put("dlhsdw",dlhsdwName);
            dataMap.put("sbdw",sbdwName);
            dataMap.put("xmmc",Util.null2String(rs.getString("xmmin")));
            String yszje = Util.null2String(rs.getString("yszje"));
            dataMap.put("xmje",yszje);

            BigDecimal zcje = getSjbxje_Project(tempRs, rs.getString("lcid"));
            dataMap.put("zcje",zcje.toString());

            BigDecimal djje = getDjje_Project(tempRs, rs.getString("lcid"));
            dataMap.put("djje",djje.toString());

            dataMap.put("sy",new BigDecimal(yszje).subtract(zcje).subtract(djje).toString());

            BigDecimal add = zcje.add(djje);
            if (add.compareTo(new BigDecimal("0"))>0){
                dataMap.put("zxl",new BigDecimal(yszje).divide(add,BigDecimal.ROUND_CEILING).toString()+"%");
            }else{
                dataMap.put("zxl","0.00%");
            }

            //获取资金渠道
            List<String> zjqd = getZjqd(condition1,rs.getString("lcjlsqjlid"));
            dataMap.put("zjqd",zjqd);

            dataList.add(dataMap);
        }
        return dataList;
    }

    /**
     * 拼接条件
     * @param kmjxj
     *            科目级下级 0/1
     * @param id
     *          科目id
     * @param dataid
     *          下级id
     * @param srlx
     *          收入类型
     * @param yslylx
     *          预算来源类型
     * @param dfczbkxm
     *          地方财政拨款项目
     * @param fzysrfl
     *          非中央收入分类
     * @return
     */
    public String splicingConditions(String kmjxj,String id,String dataid,String srlx,
                                     String yslylx,String dfczbkxm,String fzysrfl){
        StringBuffer sb = new StringBuffer();
        if (!kmjxj.isEmpty()){
            String kmxj = "";
            if (kmjxj.equals("0"))
                kmxj = new BaseBean().getPropValue("Verification","yj");
            else
                kmxj = new BaseBean().getPropValue("Verification","xj");

            if (!dataid.isEmpty()){
                String[] splitDataid = dataid.split(",");
                List<String> dataids = new LinkedList<>();
                for (String v:splitDataid){
                    dataids.add("'"+kmxj+"_"+v+"'");
                }

                sb.append(" and zyczbksr in ("+ VersionFlowUtil.joinStringBySplit(dataids,",") +") ");
            }else{
                String[] splitId = id.split(",");
                List<String> ids = new LinkedList<>();
                for (String v:splitId){
                    ids.add("'"+kmxj+"_"+v+"'");
                }

                sb.append(" and zyczbksr in ("+ VersionFlowUtil.joinStringBySplit(ids,",") +") ");
            }
        }

        if (!yslylx.isEmpty()){
            sb.append(" and yslylx like '%"+yslylx+"%' ");
        }

        if (!srlx.isEmpty()){
            sb.append(" and srlx = "+srlx+" ");
        }

        if (!fzysrfl.isEmpty()){
            if (fzysrfl.equals("5") || fzysrfl.equals("8")){
                sb.append(" and zcqd="+fzysrfl+" and dfczbkxm="+dfczbkxm );
            }else{
                sb.append(" and zcqd="+fzysrfl+" ");
            }
        }

        return sb.toString();
    }

    /**
     * 获取资金渠道
     * @param condition
     *          条件
     * @param xmid
     *          项目id
     * @return
     */
    public List<String> getZjqd(String condition,String xmid){
        String sql = "select distinct yslylx from uf_jingfeilaiyuan where lcid = "+xmid+" "+condition+"  ";

        RecordSet rs = new RecordSet();
        List<String> lyList = new LinkedList<>();
        rs.executeQuery(sql);
        while (rs.next()){
            lyList.add(rs.getString("yslylx"));
        }
        return lyList;
    }


    /**
     * 查询項目报销金额
     * @param lcid 项目流程id
     * @return
     */
    public BigDecimal getSjbxje_Project(RecordSet rs, String lcid){
        String baseSql = "SELECT ISNULL(SUM(d1.tybxje-isnull(d1.cxje,0)),0) AS sjbxje FROM dbo.uf_bxjl_kj_dt1 d1 \n" +
                "LEFT JOIN uf_bxjl_kj d ON d1.lcid=d.lcid\n" +
                "LEFT JOIN dbo.workflow_requestbase wr ON d1.lcid=wr.requestid\n" +
                "LEFT JOIN workflow_base wb ON wr.workflowid=wb.id\n" +
                "WHERE  wr.currentnodetype=3 and ysxm="+lcid;
        rs.execute(baseSql);
        if(rs.next()){
            return new BigDecimal(rs.getString("sjbxje"));
        }
        return new BigDecimal("0.00");
    }

    /**
     * 查询項目冻结金额
     * @param lcid 项目流程id
     * @return
     */
    public BigDecimal getDjje_Project(RecordSet rs, String lcid){
        String baseSql = "SELECT ISNULL(SUM(sqbxje-isnull(cxje,0)),0)  as dj FROM  (\n" +
                " SELECT wr.requestid,jl.lclx,jl.sqbxje,jl.cxje FROM dbo.uf_bxsjjl  jl LEFT JOIN workflow_requestbase wr ON jl.lcid=wr.requestid\n" +
                " WHERE ysxm="+lcid+" AND wr.currentnodetype in(1,2) )t WHERE t.requestid IS NOT NULL";
        rs.execute(baseSql);
        if(rs.next()){
            return new BigDecimal(rs.getString("dj"));
        }
        return new BigDecimal("0.00");
    }

}
